<?php

namespace app\store\controller\ditui;

use app\common\service\qrcode\Dituima;
use app\store\controller\Controller;
use app\store\model\article\Category as ArticleCategoryModel;
use app\store\model\Category as CategoryModel;
use app\store\model\sharing\Category as SharingCategoryModel;
use app\store\model\Store as StoreModel;
use app\store\model\store\Shop as ShopModel;
use app\store\model\WxappPage as WxappPageModel;
use think\Db;

class Dtactive extends Controller
{
    /** 地推专员数据列表 */
    public function active()
    {
        $paramArr = $this->request->param();

        $order = " order by page_id desc";
        $where = " where p_shopid=".$this->ad_shopid." ";

        $sql = "select * from ".getTable('wxapp_page').$where.$order;
        $list = Db::query($sql);

        //传递总数用于分页
        $sqlNum = "select count(0) as allNum from ".getTable('wxapp_page').$where;
        $allNumArr = Db::query($sqlNum);

        $shopObj = Db::name('store_shop')->where('shop_id', $this->ad_shopid)->find();

        return $this->fetch('ditui/active', ['data' =>['list'=>$list, 'shop'=>$shopObj, 'allNum'=>$allNumArr[0]['allNum']]]);
    }

    /** 添加推广二维码，生成小程序推广二维码 */
    public function setDtMa(){
        $paramArr = $this->request->param();
        $sellerId = !empty($paramArr['sellerId']) ? $paramArr['sellerId'] : 0;
        $actid = !empty($paramArr['actid']) ? $paramArr['actid'] : 0;
        $actname = !empty($paramArr['actname']) ? $paramArr['actname'] : 0;

        $actObj = Db::name('wxapp_page')->where('page_id', $actid)->find();
        if(!$actObj){
            return $this->renderError("该".$actid."地推活动不存在");
        }

        $userObj = Db::name('user')->where('user_id', $sellerId)->find();
        if(!$userObj){
            return $this->renderError('ID号未找到该地推员');
        }

        $sellerObj = Db::name('ditui_seller')->where(['ds_userid'=>$sellerId, 'ds_shopid'=>$this->ad_shopid])->find();
        if(!$sellerObj){
            return $this->renderError('该ID号不是你机构的地推专员，请先添加地推专员');
        }

        // 如果已生成了该推广码，则无需再次生成
        $maObj = Db::name('ditui_sellerma')->where(['dm_actid'=>$actid, 'dm_userid'=>$sellerId])->find();
        if($maObj){
            return $this->renderError('ID号已经生成过推广码');
        }

        // 0. 生成推广码
        $dituima = new Dituima();
        // 小程序码参数
        $path = "pages/custom/index?page_id=$actid&send_uid=$sellerId&referee_id=$sellerId";
        //$path = "pages/studycenter/index?page_id=$actid&send_uid=$sellerId&referee_id=$sellerId";
        $imgName = "ditui_".$this->ad_shopid."_".$actid."_".$sellerId;
        // 下载小程序码
        $ceneArr = ['page_id'=>$actid, 'send_uid'=>$sellerId, 'referee_id'=>$sellerId];
        $qrcodePath = $dituima->getImage($this->wxapp_id, $imgName, $path, $ceneArr);
        //ddd($qrcode);

        // 1. 添加推广二维码入库
        $inArr['dm_dsid'] = $sellerObj['ds_userid'];
        $inArr['dm_userid'] = $sellerObj['ds_userid'];
        $inArr['dm_truename'] = $sellerObj['ds_truename'];
        $inArr['dm_shopid'] = $sellerObj['ds_shopid'];
        $inArr['dm_shopname'] = $this->ad_shopname;
        $inArr['dm_actid'] = $actid;
        $inArr['dm_actname'] = $actname;
        $inArr['dm_path'] = $qrcodePath;
        $inArr['wxapp_id'] = $this->wxapp_id;
        $inArr['dm_addtime'] = date('Y-m-d H:i:s',time());
        Db::name('ditui_sellerma')->insert($inArr);

        return $this->getMaList($actid);
    }

    /** 获取地推二维码列表 */
    public function getMaList($in_page_id=0){
        $paramArr = $this->request->param();
        $page_id = !empty($paramArr['actid']) ? $paramArr['actid'] : $in_page_id;
        $maList = Db::name('ditui_sellerma')->whereIn('dm_actid', $page_id)->select()->toArray();
        $back['state'] = 'getOk';
        $back['msg'] = '添加成功';
        $back['dd'] = $maList;
        return $this->renderSuccess('获取成功', '', $back);
    }

    /** 跳转到活动编辑页面以及执行页面编辑操作，重用页面编辑的控制器逻辑 */
    public function modifyActive(){
        $paramArr = $this->request->param();
        $page_id = !empty($paramArr['actid']) ? $paramArr['actid'] : 0;

        $model = WxappPageModel::detail($page_id);
        if (!$this->request->isAjax()) {
            return $this->fetch('wxapp/page/edit', [
                'defaultData' => json_encode($model->getDefaultItems()),
                'jsonData' => json_encode($model['page_data']),
                'opts' => json_encode([
                    'catgory' => CategoryModel::getCacheTree(),
                    'sharingCatgory' => SharingCategoryModel::getCacheTree(),
                    'articleCatgory' => ArticleCategoryModel::getALL(),
                ])
            ]);
        }
        // 接收post数据
        $post = $this->request->post('data', null, null);
        if (!$model->edit(json_decode($post, true))) {
            return $this->renderError('更新失败');
        }
        return $this->renderSuccess('更新成功');
    }

    /** 跳转到商户信息编辑页面 */
    public function modifyShop(){
        $paramArr = $this->request->param();
        $shop_id = !empty($paramArr['shopid']) ? $paramArr['shopid'] : 0;
        // 门店详情
        $model = ShopModel::detail($shop_id);
        if (!$this->request->isAjax()) {
            return $this->fetch('shop/edit', compact('model'));
        }
        // 新增记录
        if ($model->edit($this->postData('shop'))) {
            return $this->renderSuccess('更新成功', url('ditui.dtactive/active'));
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }
}
